<template>
  <view class="TT">
    <ApplianceLayout
      full
      :no-action-bar="!$slots.actionBar"
      :page-style="pageStyle"
      :header-style="headerStyle"
      no-background-style
    >
      <template #header>
        <HeaderBar v-if="!showSkeleton" :control="control" :has-gas="hasGas" @open-usage-report="gotoGasChart" />
      </template>

      <view class="container" :class="{ disabled4: store.isOffline }">
        <!-- 上部分 -->
        <view class="screen-top">
          <view class="mode-title">
            <view class="pattern-left-box" @click="goSetting">
              {{ store.summerMode ? $t('TT.Detail.SummerMode.Lable') : $t('TT.Detail.WinterMode.Lable') }}
              <image src="@/pages/appliance/static/TT/ic_arrow_list1.png" class="mode-arrow"></image>
            </view>
            <image
              v-if="store.flameState === 1"
              src="@/pages/appliance/static/TT/ic_fire.png"
              class="flame-Icon"
            ></image>
          </view>
          <view class="total-set">
            <!-- 采暖-->
            <view
              class="single-set"
              :class="{ disabled: errCodeC01, hidden: store.summerMode || !store.isShowWarmTemp }"
              @click="goWarmDetail"
            >
              <view>
                <view class="set-des">
                  <image class="set-Icon" src="@/pages/appliance/static/TT/ic_boiler_ch.png"></image>
                  <view class="set-des-txt">{{
                    isMR120 ? $t('TT.Detail.WarmMr120.Title') : $t('TT.Detail.Warm.Title')
                  }}</view>
                </view>
                <view class="room-temp-view">
                  <block v-if="store.curTab === 0">
                    <view class="icon-reveal-box">
                      <image src="@/pages/appliance/static/TT/img_fire1.png"></image>
                      <view class="icon-txt">{{ $t('TT.Detail.Fire.Title') }}</view>
                    </view>
                  </block>
                  <block v-else>
                    <view class="room-temp-Int white-color">{{
                      isMR120 ? store.warmTempSetInt : store.warmTempInt
                    }}</view>
                    <view class="room-temp-dec white-color" :class="{ hidden: isMR120 }">.{{ store.warmTempDec }}</view>
                    <view class="room-state-view white-color">
                      <view class="room-unit white-color">℃</view>
                    </view>
                  </block>
                </view>
              </view>
            </view>
            <!-- 生活热水-->
            <view
              class="single-set"
              v-if="store.isShowWaterTemp"
              :class="{ disabled: errCodeC01, hidden: !store.isShowWaterTemp }"
              @click="goWaterDetail"
            >
              <view class="set-des">
                <image class="set-Icon" src="@/pages/appliance/static/TT/ic_boiler_dhw.png"></image>
                <view class="set-des-txt">{{
                  isMR120 ? $t('TT.Detail.WaterMr120.Title') : $t('TT.Detail.Water.Title')
                }}</view>
              </view>
              <view class="room-temp-view">
                <view class="room-temp-Int white-color">{{
                  isMR120 ? store.waterTempSetInt : store.waterTempInt
                }}</view>
                <view class="room-temp-dec white-color" :class="{ hidden: isMR120 }">.{{ store.waterTempDec }}</view>
                <view class="room-state-view white-color">
                  <view class="room-unit white-color">℃</view>
                </view>
              </view>
            </view>
            <image
              v-if="store.isShowWarmTemp && store.isShowWaterTemp && !store.summerMode"
              src="@/pages/appliance/static/TT/img_Line_Grey_Display&Control.png"
              class="v-line-TT"
            ></image>
          </view>
        </view>
        <!-- 房间列表 -->
        <view class="screen-bottom">
          <scroll-view
            class="scroll-view"
            scroll-y
            :style="store.summerMode || store.curTab === 1 ? 'opacity:0.4;pointer-events: none;' : 'opacity:1;'"
          >
            <view class="room-box">
              <view class="room" v-for="(item, index) in roomList" :key="index" @click="goRoomDetail(index, item)">
                <view class="room-des"> {{ $t('TT.Detail.CurrentTemp.Lable') }} </view>
                <view class="room-temp-view item-room-temp-view">
                  <view class="room-temp-Int">{{
                    isMR120 ? (item.tempInt == 409 && item.tempDec == 5 ? '-' : item.tempInt) : item.tempInt
                  }}</view>
                  <view class="room-temp-dec"
                    >.{{
                      isMR120 ? (item.tempInt == 409 && item.tempDec == 5 ? '-' : item.tempDec) : item.tempDec
                    }}</view
                  >
                  <view class="room-state-view">
                    <view class="room-unit">℃</view>
                    <image
                      v-if="item.valveState === 1"
                      class="room-state-Image"
                      src="@/pages/appliance/static/TT/Ic_heating.png"
                    ></image>
                  </view>
                </view>
                <view class="room-name-view">
                  <view class="circle-view" v-if="index === 0"></view>
                  <view class="room-name">{{ item.roomName }}</view>
                </view>
                <view v-if="isMR120 || isMR100IRFEMS" class="errcode-Icon-box">
                  <image
                    :class="{ hidden: item.errCode_key != 'H01' }"
                    src="@/pages/appliance/static/TT/ic_H01.png"
                  ></image>
                  <image
                    :class="{ hidden: item.errCode_key != 'H02' }"
                    src="@/pages/appliance/static/TT/ic_H02.png"
                  ></image>
                  <image
                    :class="{ hidden: item.errCode_key != 'H03' }"
                    src="@/pages/appliance/static/TT/ic_H03.png"
                  ></image>
                  <image
                    :class="{ hidden: item.errCode_key != 'HI' }"
                    src="@/pages/appliance/static/TT/ic_Hi.png"
                  ></image>
                  <image
                    :class="{ hidden: item.errCode_key != 'LO' }"
                    src="@/pages/appliance/static/TT/ic_Lo.png"
                  ></image>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>

        <!-- 轻微故障提示 -->
        <TopTips v-model:visible="hasLightErr" :tips-content="errTitle" show-check @check="showErrorDetail"></TopTips>
      </view>

      <!-- 严重故障提示 -->
      <Modal :visible="hasCriticalErr && !isUpgrade" :title="errTitle">
        <view class="modal-sub-tile">({{ $t('TT.Detail.Error.SubTitle.Text') }}{{ errCode }})</view>
        <view class="modal-serve">
          <text class="modal-content">{{ $t('TT.Detail.Error.Dialog.Tips.Lable.Text') }}</text>
          <text class="light-err-solve-view">{{ serviceRemind }}</text>
        </view>
        <view class="modal-btm">
          <view>
            <view class="call-label">{{ $t('TT.Detail.Error.CallServePhone.Text') }}</view>
            <view class="call-phone">400 820 6017</view>
          </view>
          <view @click="callService">
            <text>{{ $t('TT.Detail.Error.NowCall.Text') }}</text>
            <image class="call-right-arrow" src="@/pages/appliance/static/TT/ic_error_right.png"></image>
          </view>
        </view>
      </Modal>
      <!-- 轻微故障详情展示 -->
      <Modal
        :visible="showLightErr && !isUpgrade"
        :title="errTitle"
        :ok-text="$t('TT.Detail.Error.Dialog.Ok.Text')"
        @ok="showLightErr = false"
      >
        <view class="modal-sub-tile">({{ $t('TT.Detail.Error.SubTitle.Text') }}{{ errCode }})</view>
        <view class="modal-serve no-bottom">
          <text class="modal-content">{{ $t('TT.Detail.Error.Dialog.Tips.Lable.Text') }}</text>
          <text class="light-err-solve-view">{{ serviceRemind }}</text>
        </view>
      </Modal>
      <!-- MR120 OTA升级弹框 -->
      <OtaUpgrade :show="isMR120 && settings.length > 0" :ha-id="haId" :mcu-status="mcuStatus" @update="updateChange" />
      <!-- EMS OTA升级弹框 -->
      <OtaUpgradeIRF :show="isMR100IRF || isMR100IRFEMS" :mcu-status="mcuStatus" @update="updateChange" />
      <!-- settings接口报错提示弹框 -->
      <!-- <Modal
        v-model:visible="settingErrorVisible"
        title="提示"
        :cancel-text="cancleErrorText"
        :ok-text="okErrorText"
        @cancel="returnHome"
        @ok="loadAllSettingsFun"
      >
        <view>{{ settingErrorText }}</view>
      </Modal> -->
    </ApplianceLayout>

    <!-- 顶部错误提示 -->
    <NoticeBar :control="control" />
  </view>
</template>
<script setup lang="ts">
import ApplianceLayout from '@/layout/appliance/index.vue'
import HeaderBar from '../components/headerBar.vue'
import NoticeBar from '../view/notification/noticeBar.vue'
import Modal from '@/common/modal.vue'
import TopTips from '@/common/topTips.vue'
import OtaUpgrade from './otaUpgrade/otaUpgrade.vue'
import OtaUpgradeIRF from './otaUpgrade/otaUpgradeIRF.vue'

// 注意：请勿将onShareAppMessage删除
import { onShareAppMessage } from '@dcloudio/uni-app'
import { createTTControl } from '@/controller/TT'
import netconfig from '@/config/netconfig'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useTTErrorCode, type RoomListType } from './TTHelper'
import { callEventSender, showLoading, toPage } from '@/utils/mpHelper'
import { checkGas, type TTRoomDetailType } from '@/api/tt'
import { getRoomValve, TT_SETTING_BlErrCode, TT_SETTING_BlErrStr } from './SmartAssistantTool'
import { BL_Err, Room_Err } from './TTErrorCode'
import type { OemMessage } from '@/utils/socket/types'
import { loadEcharts } from './useEcharts'
import { requestSubscribeUsingComplete } from '@/utils/mpHelper'
import { useOtaUpgrade } from './otaUpgrade/otaUpgradeHelper'

showLoading(() => loadEcharts())

const control = createTTControl()
const { store } = control

const haId = ref('')
const vib = ref('')
const type = ref('')

let imgUrl = `${netconfig.ASSETSPRE_ICONS}`
const pageStyle = {
  backgroundColor: '#f4f4f6',
}
const headerStyle = {
  backgroundColor: '#ffffff',
}

// 是否显示骨架屏
const showSkeleton = computed(() => !store._datasource.loaded)

const isMR120 = computed(() => store.isMR120)
const isMR100IRF = computed(() => store.isMR100IRF)
const isMR100IRFEMS = computed(() => store.isMR100IRFEMS)
const hasGas = ref(false)

const settings = computed(() => control.store._datasource.settings as TTRoomDetailType[])
const mcuStatus = computed(() => control.store.mcuStatus as number)

const {
  roomList,
  errCodeC01,
  hasCriticalErr,
  hasLightErr,
  showLightErr,
  errTitle,
  errCode,
  userRemind,
  serviceRemind,
  addBlErr,
  delErr,
  showErr,
  addRoomErrReturnCode,
} = useTTErrorCode(settings, { isMR120, isMR100IRFEMS }, control)

const settingErrorVisible = ref(false)
const cancleErrorText = ref('')
const okErrorText = ref('')
const settingErrorText = ref('')

onLoad((query: any) => {
  haId.value = query?.haId
  vib.value = query?.vib
  type.value = query?.type
  listenMessages()
})

watch(
  () => store.isOffline,
  (isOffline) => {
    if (isOffline || haId.value.split('-')[1] === 'MR10010528') return
    checkDeviceHasGas()
  }
)

const isUpgrade = ref(false)
function updateChange(value: boolean) {
  isUpgrade.value = value
}

/**
 * 加载settings数据
 */
// async function loadAllSettingsFun() {
//   const res = await getAllSetting(haId.value, true)
//   if (res.code === 0) {
//     control.store._datasource.setting = res.data.settings
//     settingErrorVisible.value = false
//     cancleErrorText.value = ''
//     okErrorText.value = ''
//     settingErrorText.value = ''
//   } else if ([950002, 950003, 950004, 950005].includes(res.code)) {
//     settingErrorVisible.value = true
//     cancleErrorText.value = '取消'
//     okErrorText.value = '重试'
//     settingErrorText.value = '数据请求超时，请重试。'
//   } else {
//     settingErrorVisible.value = true
//     okErrorText.value = '重试'
//     settingErrorText.value = '服务器错误'
//   }
// }

/**
 * 跳转采暖页面
 */
async function goWarmDetail() {
  if (roomList.value?.length === 0) return
  const res = await toPage('/pages/appliance/TT/warmSet/warmSet', {
    haId: haId.value,
  })
  callEventSender(res.eventChannel, 'control', control)
}
/**
 * 跳转生活热水
 */
async function goWaterDetail() {
  if (roomList.value?.length === 0) return
  const res = await toPage('/pages/appliance/TT/waterSet/waterSet', {
    haId: haId.value,
  })
  callEventSender(res.eventChannel, 'control', control)
}
/**
 * 跳转房间页面
 */
async function goRoomDetail(index: number, item: RoomListType) {
  let url = ''
  if (isMR120.value || isMR100IRFEMS.value) {
    url = `/pages/appliance/TT/newRoomSet/newRoomSet`
  } else {
    url = `/pages/appliance/TT/roomSet/roomSet`
  }
  const res = await toPage(url, {
    haId: haId.value,
    curIndex: index,
    name: item.name,
    roomList: JSON.stringify(roomList.value),
  })
  callEventSender(res.eventChannel, 'control', control)
}
/**
 * 跳转家电设置页面
 */
const guest = computed(() => store.detail?.guest)
const connected = computed(() => store.detail?.connected)
const remoteControl = computed(() => store.remoteControl)
const remoteStart = computed(() => store.remoteStart)
const name = computed(() => store.detail?.name)
async function goSetting() {
  // 一次性消息订阅
  await requestSubscribeUsingComplete([netconfig.DeviceStateId])
  let pageUrl = '/pages/appliance/settings/applianceSettings'

  return toPage(pageUrl, {
    haId: haId.value,
    vib: vib.value,
    type: type.value,
    guest: guest.value,
    connected: connected.value,
    remoteControl: remoteControl.value,
    remoteStart: remoteStart.value,
    name: name.value,
  })
}
/**
 * 呼叫客服
 */
function callService() {
  uni.makePhoneCall({
    phoneNumber: '400 820 6017',
  })
}
/**
 * 展示轻微报错详情
 */
function showErrorDetail() {
  showLightErr.value = true
}
/**
 * 获取设备是否有历史燃气量
 */
async function checkDeviceHasGas() {
  const res = await checkGas(haId.value)
  if (res.code === 0) {
    hasGas.value = res.data as unknown as boolean
  }
}
/**
 * 跳转燃气消耗量
 */
function gotoGasChart() {
  if (store.isOffline) return
  toPage(`/pages/appliance/TT/newGasChart/newGasChart?haId=${haId.value}`)
}

/**
 * 处理错误码
 */
function listenMessages() {
  control.remote.addBatchObserves([
    {
      matcher: (msg: { key: string }) =>
        ['BSH.Common.Setting.Err', TT_SETTING_BlErrCode, TT_SETTING_BlErrStr].includes(msg.key),
      handler: (msg) => handelBLErrCode(msg),
    },
    {
      matcher: (msg: { key: string }) => [TT_SETTING_BlErrStr].includes(msg.key),
      handler: (msg) => handelBLErrStr(msg),
    },
    {
      matcher: (msg: { key: string }) =>
        /BSH.Common.Setting.Rm[0-9]{1,2}Temp/.test(msg.key) ||
        /SmartAssistant.TT.Setting.Rm[0-9]{1,2}Temp/.test(msg.key),
      handler: (msg) => updateRoomList(msg as OemMessage.MessageItem, 'Temp'),
    },
    {
      matcher: (msg: { key: string }) => /SmartAssistant.TT.Setting.Rm[0-9]{1,2}State/.test(msg.key),
      handler: (msg) => updateRoomList(msg as OemMessage.MessageItem, 'State'),
    },
    {
      matcher: (msg: { key: string }) =>
        /BSH.Common.Setting.Rm[0-9]{1,2}ErrCode/.test(msg.key) ||
        /SmartAssistant.TT.Setting.Rm[0-9]{1,2}ErrCode/.test(msg.key),
      handler: (msg) => updateRoomList(msg as OemMessage.MessageItem, 'ErrCode'),
    },
    {
      matcher: (msg: { key: string }) =>
        /BSH.Common.Setting.Rm[0-9]{1,2}Valve/.test(msg.key) ||
        /SmartAssistant.TT.Setting.Rm[0-9]{1,2}Valve/.test(msg.key),
      handler: (msg) => updateRoomList(msg as OemMessage.MessageItem, 'ErrCode'),
    },
  ])
}
function handelBLErrCode(msg: any) {
  if (Number(msg.value) !== 0) {
    addBlErr(BL_Err, msg.value, 'Bl_ErrCode')
  } else {
    delErr('Bl_ErrCode')
  }
  showErr()
}
function handelBLErrStr(msg: any) {
  if (Number(msg.value) !== 0) {
    addBlErr(BL_Err, msg.value, 'Bl_ErrStr')
  } else {
    delErr('Bl_ErrStr')
  }
  showErr()
}
function updateRoomList(item: OemMessage.MessageItem, type: string) {
  if (!item.key) return
  let key = item.key
  key = key.replace('BSH.Common.Setting.', '')
  key = key.replace('SmartAssistant.TT.Setting.', '')
  key = key.replace(type, '')
  let roomListTemp = JSON.parse(JSON.stringify(roomList.value))
  for (let i = 0; i < roomListTemp.length; i++) {
    if (roomListTemp[i].key == key) {
      if (type == 'Temp') {
        let newValue = Math.abs(item.value as number)
        roomListTemp[i].tempInt =
          Number(item.value) < 0 ? '-' + parseInt(newValue / 10 + '') : parseInt(newValue / 10 + '')
        roomListTemp[i].tempDec = newValue % 10
      } else if (type == 'Valve') {
        roomListTemp[i].valveState = item.value
      } else if (type == 'State') {
        roomListTemp[i].valveState = getRoomValve(item.value as string)
      } else if (type == 'ErrCode') {
        let errCode_key = ''
        if (Number(item.value) != 0) {
          errCode_key = addRoomErrReturnCode(Room_Err, item.value as string, item.param)
        } else {
          delErr(item.param)
        }
        roomListTemp[i].errCode_key = errCode_key
        showErr()
      }
    }
  }
  roomList.value = roomListTemp
}
/**
 * 返回首页
 */
function returnHome() {
  uni.navigateBack({
    delta: 1,
  })
}
</script>
<style scoped lang="less">
@import './style/TT.less';
</style>
